import createError from "http-errors";
import express from "express";
import path from "path";
import cookieParser from "cookie-parser";
// import logger from "morgan";
// import fs from "fs";
let app = express();

app.set("views", path.join("./", "views"));
app.set("view engine", "ejs");

// app.use(logger("short", { stream: fs.createWriteStream(path.join("./", "log.log"), { flags: "a" }) }));
app.use(express.json({ limit: "3mb" })); //limit 请求体最大值(默认100kb)
app.use(cookieParser());

// app.use(express.static(path.join("./", "appStatic"))); //平台静态资源
// app.use("/assets", express.static(path.join("./", "appStatic/visualApp/assets"))); //应用静态资源
// app.use("/assets/resource", express.static(path.join("./", "appStatic/visualApp/assets"))); //应用静态资源
app.use(function (req, res, next) {
  console.log("[请求拦截]", req.method, req.url, req.header("token"));
  // if (req.method == "OPTIONS" || req.header("token")) {
  //   console.log(req.url, "请求类型为OPTIONS或有token,允许跨域访问");
  //   res.header("Access-Control-Allow-Origin", "*"); // 设置受信域名(*为所有域名)
  //   res.header("Access-Control-Allow-Methods", "*"); // 允许响应类型
  //   res.header("Access-Control-Allow-Headers", "*");
  //   res.header("Access-Control-Expose-Headers", "*");
  //   res.header("X-Powered-By", " 3.2.1");
  //   next();
  // } else {
  //   console.log("没有token禁止跨域访问");
  //   next();
  // }
  next();
});

import ax from "./routes/ax/ax.js";
app.use(ax);

// import api from "./routes/api.js";
// app.use("/api", api);

app.options("/test", (req, res) => {
  //向客户端发送json对象
  console.log("options token", req.header("token"));
  res.send(req.header("token"));
});

app.get("/test", (req, res) => {
  //向客户端发送json对象
  console.log("token", req.header("token"));
  res.send(
    req.header("token")
      ? {
          name: "zs",
          age: 20,
          gender: "男",
          token: req.header("token")
        }
      : "没有token"
  );
});
app.post("/test", (req, res) => {
  //向客户端发送json对象
  console.log("token", req.header("token"));
  res.send(
    req.header("token")
      ? {
          method: "post",
          age: 20,
          gender: "男",
          token: req.header("token")
        }
      : "post 没有token"
  );
  console.log("token1111", req.header("token"));
});

app.get("/apiDoc", (req, res, next) => {
  const replaceAll = function (find, replace, str) {
    const find2 = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
    return str.replace(new RegExp(find2, "g"), replace);
  };
  function parseHandle(prefix, urls, handle) {
    if (!handle) {
      return;
    }
    handle.stack.forEach((layer) => {
      let reg;
      let str;
      if (layer.name === "router") {
        let llPrefix = prefix;
        reg = layer.regexp;
        str = reg.toString();
        str = replaceAll("?", "", str);
        str = replaceAll("?", "", str);
        str = replaceAll("^", "", str);
        str = replaceAll("/i", "/", str);
        str = replaceAll("\\", "", str);
        str = replaceAll("|", "", str);
        str = replaceAll("&", "", str);
        str = replaceAll("$", "", str);
        str = replaceAll("(", "", str);
        str = replaceAll(")", "", str);
        str = replaceAll("=", "", str);
        str = replaceAll("//", "/", str);
        str = replaceAll("//", "/", str);
        str = str.substr(0, str.length - 1);
        const matchs = layer.regexp.toString().match(/\\(\/[^\/\?]*)\\\//);
        llPrefix = str;
        parseHandle(llPrefix, urls, layer.handle);
      }
      if (layer.name === "bound dispatch") {
        const uri = prefix + layer.route.path;
        if (uri.indexOf("*") < 0) {
          urls.push(prefix + layer.route.path);
          console.log("uri: " + uri);
        }
      }
    });
  }

  var stack = [];
  parseHandle("*", stack, app._router);
  res.json({ apiDoc: stack });
});
app.use((req, res, next) => next(createError(404)));

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

export default app;
// module.exports = app;
